package com.shensi.appCollect.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shensi.appCollect.dao.PhysicalCardBalanceMapper;
import com.shensi.appCollect.dao.PhysicalCardMapper;
import com.shensi.appCollect.dao.StationMapper;
import com.shensi.appCollect.enums.*;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.pojo.dto.PhysicalCardSecretKeyDto;
import com.shensi.appCollect.service.CardBatchService;
import com.shensi.appCollect.service.EnterpriseService;
import com.shensi.appCollect.service.PhysicalCardBalanceService;
import com.shensi.appCollect.service.ReductionActivityBalanceRecordService;
import com.shensi.appCollect.utils.StringUtils;
import com.shensi.appCollect.utils.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @date 2023/12/7
 */
@Service
@Slf4j
public class PhysicalCardBalanceServiceImpl extends ServiceImpl<PhysicalCardBalanceMapper, PhysicalCardBalance> implements PhysicalCardBalanceService {

    @Autowired
    private PhysicalCardMapper physicalCardMapper;

    @Resource
    private PhysicalCardBalanceMapper physicalCardBalanceMapper;

    @Autowired
    private CardBatchService cardBatchService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private ReductionActivityBalanceRecordService reductionActivityBalanceRecordService;

    @Override
    public PhysicalCardBalance physicalCardWxRecharge(PhysicalCardBalance physicalCardBalance) {
        PhysicalCard physicalCard = physicalCardMapper.selectByPhysicalCardNo(physicalCardBalance.getPhysicalCardNo());
        // 定额卡 不能充值
        CardBatch cardBatch = cardBatchService.getById(physicalCard.getBatchId());
        if (Objects.isNull(cardBatch) || PhysicalCardTypeEnum.DEK.getValue().equals(cardBatch.getPhysicalCardType())) {
            throw new CustomException("定额卡不能充值");
        }
        // 充值油站属于绑定油站
        checkStationId(physicalCard.getStationId(),physicalCardBalance.getStationId());

        return createOrder(physicalCardBalance);
    }

    private void checkStationId(String stationIds, String currStationId){
        if(StringUtils.isEmpty(stationIds) || StringUtils.isEmpty(currStationId)){
            throw new CustomException("实体卡充值--油站不存在");
        }
        List<String> list = Arrays.stream(stationIds.split(",")).collect(Collectors.toList());
        if(!list.contains(currStationId)){
            throw new CustomException("实体卡充值--油站不属于充值油站");
        }
    }

    private PhysicalCardBalance createOrder(PhysicalCardBalance physicalCardBalance){
        Station station = enterpriseService.selectStationById(Integer.valueOf(physicalCardBalance.getStationId()));

        physicalCardBalance.setBalanceNo(StringUtils.generateOrdNo());
        physicalCardBalance.setBalanceType(BalanceTypeEnum.RECHARGE.getValue());
        physicalCardBalance.setEnterpriseId(Long.valueOf(station.getEnterpriseId()));
        physicalCardBalance.setEnterpriseName(station.getEnterprise().getEnterpriseName());
        physicalCardBalance.setStationName(station.getStationName());
        physicalCardBalance.setStatus("0");
        physicalCardBalance.setCreateTime(new Date());
        physicalCardBalance.setIsDeleted("0");
        physicalCardBalance.setPayment(PhysicalCardPaymentEnum.WX.getValue());
        physicalCardBalance.setRefundStatus("1");

        physicalCardBalanceMapper.insertSelective(physicalCardBalance);
        reductionActivityBalanceRecordService.createBalanceRecord(physicalCardBalance.getAmount(),physicalCardBalance.getPhysicalCardNo(),Long.valueOf(station.getEnterpriseId()),"wx",station.getStationId().longValue());
        return physicalCardBalance;
    }

    @Override
    public PhysicalCardBalance selectPhysicalCardBalance(PhysicalCardBalance physicalCardBalance) {
        return physicalCardBalanceMapper.selectPhysicalCardBalance(physicalCardBalance);
    }

    @Override
    @Transactional
    public int updatePhysicalCardBalance(PhysicalCardBalance physicalCardBalance) {
        if(Objects.isNull(physicalCardBalance) || StringUtils.isEmpty(physicalCardBalance.getBalanceNo())
                || StringUtils.isEmpty(physicalCardBalance.getPhysicalCardNo())){
            throw new CustomException("实体卡微信充值记录请求参数异常");
        }
        if(Objects.isNull(physicalCardBalance.getAmount())){
            throw new CustomException("实体卡微信充值记录请求没有充值金额");
        }

        PhysicalCard physicalCard = physicalCardMapper.selectByPhysicalCardNo(physicalCardBalance.getPhysicalCardNo());

        PhysicalCard newPhysicalCard = new PhysicalCard();
        newPhysicalCard.setPhysicalCardNo(physicalCardBalance.getPhysicalCardNo());

        PhysicalCardBalance balance = new PhysicalCardBalance();
        balance.setBalanceNo(physicalCardBalance.getBalanceNo());
        balance.setAmount(physicalCardBalance.getAmount());
        balance.setStatus(BalanceStatusEnum.SUCCESS.getCode());
        balance.setTransactionId(physicalCardBalance.getTransactionId());
        balance.setMerchantsNumber(physicalCardBalance.getMerchantsNumber());

        if(Objects.isNull(physicalCard.getPhysicalCardAmount()) || (BigDecimal.ZERO.compareTo(physicalCard.getPhysicalCardAmount()) == 0)){
            newPhysicalCard.setPhysicalCardAmount(physicalCardBalance.getAmount());
            balance.setBalanceAmount(physicalCardBalance.getAmount());
        } else {
            newPhysicalCard.setPhysicalCardAmount(physicalCard.getPhysicalCardAmount().add(physicalCardBalance.getAmount()));
            balance.setBalanceAmount(physicalCard.getPhysicalCardAmount().add(physicalCardBalance.getAmount()));
        }
        physicalCardMapper.updateByPrimaryKeySelective(newPhysicalCard);
        return physicalCardBalanceMapper.updatePhysicalCardBalance(balance);
    }

    @Override
    public PhysicalCardSecretKeyDto addPhysicalCardBalance(PhysicalCardBalance physicalCardBalance) {
        if(Objects.isNull(physicalCardBalance) || StringUtils.isEmpty(physicalCardBalance.getPhysicalCardNo())){
            throw new CustomException("addPhysicalCardBalance实体卡充值数据异常");
        }

        if(StringUtils.isEmpty(physicalCardBalance.getStationId())){
            throw new CustomException("实体卡充值--油站不存在");
        }

        Station station = stationMapper.selectStationById(Integer.valueOf(physicalCardBalance.getStationId()));
        physicalCardBalance.setStationName(station.getStationName());


        // 充值时才需要生成订单号  消费时订单号和订单表一致
        String balanceNo = "";
        if(BalanceTypeEnum.RECHARGE.getValue().equals(physicalCardBalance.getBalanceType())
                || BalanceTypeEnum.RATION_RECHARGE.getValue().equals(physicalCardBalance.getBalanceType())) {
            // 生成订单号
            Random random = new Random();
            String result = "";
            for (int i = 0; i < 6; i++) {
                result += random.nextInt(10);
            }
            balanceNo = System.currentTimeMillis() + result;
            physicalCardBalance.setBalanceNo(balanceNo);
        }
        physicalCardBalance.setCreateTime(new Date());
        log.info("实体卡充值，PhysicalCardBalanceServiceImpl.addPhysicalCardBalance: [{}]", JSONObject.toJSONString(physicalCardBalance));
        physicalCardBalanceMapper.insertSelective(physicalCardBalance);

        PhysicalCardSecretKeyDto physicalCardSecretKeyDto = new PhysicalCardSecretKeyDto();
        physicalCardSecretKeyDto.setOrderNo(balanceNo);
        return physicalCardSecretKeyDto;
    }

    @Override
    public CustomerCardUseRecord getPhysicalCardBalanceByOrdNo(String ordNo) {
        return physicalCardBalanceMapper.getPhysicalCardBalanceByOrdNo(ordNo);
    }
}
